package com.example.zhaojianxu.signin.englishgame.start

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import com.example.zhaojianxu.signin.R
import com.example.zhaojianxu.signin.bean.BaseActivity
import com.example.zhaojianxu.signin.common.constance.ComConstance
import com.example.zhaojianxu.signin.common.http.HttpUtil
import com.example.zhaojianxu.signin.englishgame.constance.Constance
import com.example.zhaojianxu.signin.englishgame.http.EGStartEntity
import de.greenrobot.event.EventBus
import kotlinx.android.synthetic.main.activity_start.*
import kotlinx.android.synthetic.main.common_title_bar.*
import kotlinx.coroutines.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.text.SimpleDateFormat
import java.util.*

class StartActivity : BaseActivity() {

    var mAdapter: StartAdapter? = null
    var job: Job? = null
    var mStatus: Boolean = true
    var mProgress: Int = 100

    var startTime = 0L
    var endTime = 0L

    init {
        Constance.KEY = ""
        Constance.VALUE = ""
        Constance.COUNT = 0
    }

    override fun initView() {
        common_back.setOnClickListener {
            finish()
        }

        common_title.text = "游戏"
        common_setting.visibility = View.GONE

        activity_start_2.setOnClickListener {
            mStatus = true
        }
        activity_start_3.setOnClickListener {
            mStatus = false
        }
        activity_start_4.setOnClickListener {
            initData()
            activity_start_6.visibility = View.GONE
            activity_start_5.visibility = View.VISIBLE
            mStatus = false
            mProgress = 100
            activity_start_1.progress = mProgress
            mStatus = true
            Constance.COUNT = 0
        }

        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        activity_start_5.layoutManager = linearLayoutManager


        mAdapter = StartAdapter()
        activity_start_5.adapter = mAdapter

        activity_start_1.progress = mProgress

        job = CoroutineScope(Dispatchers.Default).launch {
            while (true) {
                delay(600)
                if (mStatus) mProgress -= 1
                withContext(Dispatchers.Main) {
                    activity_start_1.progress = mProgress
                    if (mProgress <= 0) {
                        activity_start_6.visibility = View.VISIBLE
                        activity_start_5.visibility = View.GONE
                    }
                }
                if (mProgress <= 0) {
                    return@launch
                }
            }
        }
    }

    override fun initData() {
        HttpUtil.instance.getEnglishGameApi()?.postQueryStart()?.enqueue(object : Callback<MutableList<EGStartEntity>> {
            override fun onFailure(call: Call<MutableList<EGStartEntity>>, t: Throwable) {
                Log.e("StartActivity", "${t.message}")
            }

            override fun onResponse(
                call: Call<MutableList<EGStartEntity>>,
                response: Response<MutableList<EGStartEntity>>
            ) {
                if (response.isSuccessful && response.body() != null && response.body()?.isEmpty() == false) {
                    mAdapter?.bindData(dataFix(response.body()))
                    startTime = Calendar.getInstance().timeInMillis

                }
            }

        })
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_start)

        EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        job?.cancel()
        EventBus.getDefault().post(UnregisterEvent())
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    fun dataFix(list: MutableList<EGStartEntity>?): MutableList<EGStartEntity> {
        var temp1 = mutableListOf<String>()

        for (it in list!!) {
            temp1.add(it.english!!)
        }

        temp1 = shffle(temp1)

        for (position in 0 until list.size) {
            list[position].mokeE = temp1[position]
        }

        for (position in 0 until list.size) {
            for (i in 0 until list.size) {
                if (list[position].mokeE.equals(list[i].english)) {
                    list[position].mokeC = list[i].china
                }
            }

        }


        return list
    }

    fun shffle(list: MutableList<String>): MutableList<String> {
        for (i in (list.size - 1) downTo 0) {
            var randomIdx = Math.floor(Math.random() * (i + 1))
            var itemAtIdx = list[randomIdx.toInt()]
            list[randomIdx.toInt()] = list[i]
            list[i] = itemAtIdx
        }

        return list
    }

    fun onEvent(event: StartVisibilityEvent) {

        ++Constance.COUNT
        Log.d("TAGGGGG","this ${this@StartActivity}  count = ${Constance.COUNT}   itemCount = ${mAdapter?.itemCount} ")
        if (Constance.COUNT == mAdapter?.itemCount) {
            endTime = Calendar.getInstance().timeInMillis
            mStatus = false
            activity_start_6.visibility = View.VISIBLE
            activity_start_5.visibility = View.GONE
            upLoadCode()
        }
    }

    fun upLoadCode() {
        val currentDate = SimpleDateFormat("yyyy-MM-dd").format(Date())
        HttpUtil.instance.getEnglishGameApi()?.postUploadCode(ComConstance.UID, ((endTime - startTime).toInt()), currentDate)
            ?.enqueue(object : Callback<String> {
                override fun onFailure(call: Call<String>, t: Throwable) {
                }

                override fun onResponse(call: Call<String>, response: Response<String>) {
                }

            })
    }
}
